import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Card, Descriptions, Button, Tag, Timeline, Steps, Space, Spin, message } from 'antd';
import { ArrowLeftOutlined, PrinterOutlined, EditOutlined } from '@ant-design/icons';

const { Step } = Steps;

interface OrderDetail {
  id: number;
  orderNo: string;
  customerName: string;
  customerPhone: string;
  customerEmail?: string;
  totalAmount: number;
  status: 'pending' | 'paid' | 'shipped' | 'completed' | 'cancelled';
  paymentMethod: 'alipay' | 'wechat' | 'bank';
  createTime: string;
  payTime?: string;
  shipTime?: string;
  completeTime?: string;
  shippingAddress: string;
  products: OrderProduct[];
  logistics?: LogisticsInfo;
}

interface OrderProduct {
  id: number;
  name: string;
  price: number;
  quantity: number;
  total: number;
  image?: string;
}

interface LogisticsInfo {
  company: string;
  trackingNo: string;
  status: string;
  updates: LogisticsUpdate[];
}

interface LogisticsUpdate {
  time: string;
  description: string;
  location: string;
}

const OrderDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [order, setOrder] = useState<OrderDetail | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    loadOrderDetail();
  }, [id]);

  const loadOrderDetail = async () => {
    if (!id) return;
    
    setLoading(true);
    try {
      // 模拟 API 调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 模拟数据
      const mockOrder: OrderDetail = {
        id: parseInt(id),
        orderNo: `ORDER20240115000${id}`,
        customerName: '张三',
        customerPhone: '13800138000',
        customerEmail: 'zhangsan@example.com',
        totalAmount: 7999,
        status: 'shipped',
        paymentMethod: 'alipay',
        createTime: '2024-01-15 10:30:00',
        payTime: '2024-01-15 10:35:00',
        shipTime: '2024-01-15 14:20:00',
        shippingAddress: '北京市朝阳区某某街道123号 邮编: 100000',
        products: [
          {
            id: 1,
            name: 'iPhone 15 Pro',
            price: 7999,
            quantity: 1,
            total: 7999,
            image: 'https://via.placeholder.com/60x60?text=iPhone',
          },
        ],
        logistics: {
          company: '顺丰速运',
          trackingNo: 'SF1234567890',
          status: 'in_transit',
          updates: [
            {
              time: '2024-01-15 14:20:00',
              description: '已发货',
              location: '北京仓库',
            },
            {
              time: '2024-01-15 16:30:00',
              description: '已揽收',
              location: '北京分拨中心',
            },
            {
              time: '2024-01-16 08:15:00',
              description: '运输中',
              location: '前往朝阳区分部',
            },
          ],
        },
      };
      
      setOrder(mockOrder);
    } catch (error) {
      message.error('加载订单详情失败');
      navigate('/orders/list');
    } finally {
      setLoading(false);
    }
  };

  const getStatusColor = (status: string) => {
    const colors = {
      pending: 'orange',
      paid: 'blue',
      shipped: 'purple',
      completed: 'green',
      cancelled: 'red',
    };
    return colors[status as keyof typeof colors] || 'default';
  };

  const getStatusText = (status: string) => {
    const texts = {
      pending: '待支付',
      paid: '已支付',
      shipped: '已发货',
      completed: '已完成',
      cancelled: '已取消',
    };
    return texts[status as keyof typeof texts] || status;
  };

  const getPaymentMethodText = (method: string) => {
    const texts = {
      alipay: '支付宝',
      wechat: '微信支付',
      bank: '银行卡',
    };
    return texts[method as keyof typeof texts] || method;
  };

  const getCurrentStep = (status: string) => {
    const steps = {
      pending: 0,
      paid: 1,
      shipped: 2,
      completed: 3,
      cancelled: -1,
    };
    return steps[status as keyof typeof steps] || 0;
  };

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: 50 }}>
        <Spin size="large" />
      </div>
    );
  }

  if (!order) {
    return <div>订单不存在</div>;
  }

  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <Button 
          type="text" 
          icon={<ArrowLeftOutlined />} 
          onClick={() => navigate('/orders/list')}
        >
          返回订单列表
        </Button>
      </div>

      <Card
        title={`订单详情 - ${order.orderNo}`}
        extra={
          <Space>
            <Button icon={<PrinterOutlined />}>打印</Button>
            <Button type="primary" icon={<EditOutlined />}>编辑</Button>
          </Space>
        }
      >
        {/* 订单进度 */}
        <Card type="inner" title="订单进度" style={{ marginBottom: 16 }}>
          <Steps current={getCurrentStep(order.status)}>
            <Step title="待支付" description={order.createTime} />
            <Step title="已支付" description={order.payTime} />
            <Step title="已发货" description={order.shipTime} />
            <Step title="已完成" description={order.completeTime} />
          </Steps>
        </Card>

        <div style={{ display: 'flex', gap: 16, marginBottom: 16 }}>
          {/* 订单信息 */}
          <Card type="inner" title="订单信息" style={{ flex: 1 }}>
            <Descriptions column={1} size="small">
              <Descriptions.Item label="订单号">{order.orderNo}</Descriptions.Item>
              <Descriptions.Item label="订单状态">
                <Tag color={getStatusColor(order.status)}>
                  {getStatusText(order.status)}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="订单金额">
                ¥{order.totalAmount.toLocaleString()}
              </Descriptions.Item>
              <Descriptions.Item label="支付方式">
                {getPaymentMethodText(order.paymentMethod)}
              </Descriptions.Item>
              <Descriptions.Item label="创建时间">{order.createTime}</Descriptions.Item>
              <Descriptions.Item label="支付时间">{order.payTime || '-'}</Descriptions.Item>
              <Descriptions.Item label="发货时间">{order.shipTime || '-'}</Descriptions.Item>
            </Descriptions>
          </Card>

          {/* 客户信息 */}
          <Card type="inner" title="客户信息" style={{ flex: 1 }}>
            <Descriptions column={1} size="small">
              <Descriptions.Item label="客户姓名">{order.customerName}</Descriptions.Item>
              <Descriptions.Item label="手机号码">{order.customerPhone}</Descriptions.Item>
              <Descriptions.Item label="电子邮箱">{order.customerEmail || '-'}</Descriptions.Item>
              <Descriptions.Item label="收货地址">
                <div style={{ wordBreak: 'break-all' }}>
                  {order.shippingAddress}
                </div>
              </Descriptions.Item>
            </Descriptions>
          </Card>
        </div>

        {/* 商品清单 */}
        <Card type="inner" title="商品清单" style={{ marginBottom: 16 }}>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr style={{ backgroundColor: '#fafafa' }}>
                <th style={{ padding: '8px', textAlign: 'left', border: '1px solid #f0f0f0' }}>商品</th>
                <th style={{ padding: '8px', textAlign: 'center', border: '1px solid #f0f0f0' }}>单价</th>
                <th style={{ padding: '8px', textAlign: 'center', border: '1px solid #f0f0f0' }}>数量</th>
                <th style={{ padding: '8px', textAlign: 'center', border: '1px solid #f0f0f0' }}>小计</th>
              </tr>
            </thead>
            <tbody>
              {order.products.map(product => (
                <tr key={product.id}>
                  <td style={{ padding: '8px', border: '1px solid #f0f0f0' }}>
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                      <img 
                        src={product.image} 
                        alt={product.name}
                        style={{ width: 40, height: 40, marginRight: 8, objectFit: 'cover' }}
                      />
                      {product.name}
                    </div>
                  </td>
                  <td style={{ padding: '8px', textAlign: 'center', border: '1px solid #f0f0f0' }}>
                    ¥{product.price.toLocaleString()}
                  </td>
                  <td style={{ padding: '8px', textAlign: 'center', border: '1px solid #f0f0f0' }}>
                    {product.quantity}
                  </td>
                  <td style={{ padding: '8px', textAlign: 'center', border: '1px solid #f0f0f0' }}>
                    ¥{product.total.toLocaleString()}
                  </td>
                </tr>
              ))}
            </tbody>
            <tfoot>
              <tr>
                <td 
                  colSpan={3} 
                  style={{ padding: '8px', textAlign: 'right', border: '1px solid #f0f0f0', fontWeight: 'bold' }}
                >
                  总计：
                </td>
                <td 
                  style={{ padding: '8px', textAlign: 'center', border: '1px solid #f0f0f0', fontWeight: 'bold', color: '#ff4d4f' }}
                >
                  ¥{order.totalAmount.toLocaleString()}
                </td>
              </tr>
            </tfoot>
          </table>
        </Card>

        {/* 物流信息 */}
        {order.logistics && (
          <Card type="inner" title="物流信息">
            <Descriptions column={2} size="small" style={{ marginBottom: 16 }}>
              <Descriptions.Item label="物流公司">{order.logistics.company}</Descriptions.Item>
              <Descriptions.Item label="运单号码">{order.logistics.trackingNo}</Descriptions.Item>
            </Descriptions>
            
            <Timeline>
              {order.logistics.updates.map((update, index) => (
                <Timeline.Item key={index}>
                  <div>
                    <div style={{ fontWeight: 'bold' }}>{update.description}</div>
                    <div style={{ color: '#666' }}>{update.location}</div>
                    <div style={{ color: '#999', fontSize: '12px' }}>{update.time}</div>
                  </div>
                </Timeline.Item>
              ))}
            </Timeline>
          </Card>
        )}
      </Card>
    </div>
  );
};

export default OrderDetail;